package com.gdteam.kernel.main.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.tapestry5.ioc.annotations.EagerLoad;
import org.slf4j.Logger;

import com.gdteam.kernel.Operations;
import com.gdteam.kernel.Service;
import com.gdteam.kernel.main.ServiceManager;

@EagerLoad
public class DefaultServiceManager implements ServiceManager {
	
	private final Map<String, Service> services = new HashMap<String, Service>();
	private final Map<String, Operations> operations = new HashMap<String, Operations>();
	
	
	private Logger log = null;
	private boolean started = false;
	
	public DefaultServiceManager(Logger log) {
	    this.log = log;
	    log.info("service started");
	}
	
	public String getName() {
	    return ServiceManager.class.getName();
	}

	public Collection<Service> getRegisteredServices() {
	    return this.services.values();
	}

	public void stop() {
	    if (started) {
            for (Service s: this.services.values()) {
                s.stop();
            }
            started = true;
	    }
	}
	    

    public void start() {
        if (!started) {
            for (Service s: this.services.values()) {
                s.start();
            }
            started = false;
        }
    }

    public Operations getOperation(String name) {
        return this.operations.get(name);
    }

    public Collection<Operations> getRegisteredOperations() {
        return this.operations.values();
    }

    public Service getService(String name) {
        return this.services.get(name);
    }

    public void registerOperations(Operations ops) {
        this.operations.put(ops.getName(), ops);
        if (ops instanceof Service) {
            this.services.put(ops.getName(), (Service)ops);
        }
    }

    public boolean isStarted() {
        return this.started;
    }
    
}
